package tt.dz.service.imp.middleware;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tt.dz.dao.ext.charger.OmsChargerChargeBillRecordDao;
import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.charger.OmsChargerPulseRecordDao;
import tt.dz.dao.ext.charger.OmsChargerStateAlternateDao;
import tt.dz.dao.ext.charger.OmsChargerTelemetryRecordDao;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerChargeBillRecord;
import tt.dz.entity.charger.OmsChargerPulseRecord;
import tt.dz.entity.charger.OmsChargerStateAlternate;
import tt.dz.entity.charger.OmsChargerTelemetryRecord;
import tt.dz.service.middleware.UploadDataService;
import tt.dz.util.StringUtil;
@Service @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UploadDataServiceImpl implements UploadDataService{
	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsChargerTelemetryRecordDao OmsChargerTelemetryRecordDao;
	@Resource
	OmsChargerPulseRecordDao omsChargerPulseRecordDao;
	@Resource
	OmsChargerChargeBillRecordDao omsChargerChargeBillRecordDao;
	@Resource
	OmsChargerStateAlternateDao omsChargerStateAlternateDao;
	
	@Override
	//所有字段位置按照1.3协议中充电上传报文来重新获取
	public String uploadTelemeter(Map<String,String> map) {
		String data,chargerId,code,msg; 
		data = map.get("data");
		chargerId = map.get("chargerId");
		float thisVoltage = StringUtil.float16to10ByParamDesc(data.substring(50,56), 100); //*充电电压(V)系数为0.01:低字节在前，高字节在后，数据放大100倍，如0x1D 0x57 0x00,表示实际数据为223.01V
		float thisElectricity = StringUtil.float16to10ByParamDesc(data.substring(56, 62), 100); //电流与电压类似
//		int this_hour = StringUtil.int16to10ByParam(data.substring(62, 68), 1);//充电时间
		int this_minute = (int)StringUtil.float16to10ByParamDesc(data.substring(68, 74), 1);//充电时间
		//*输出功率(W)	BIN码	3	系数为1	低字节在前，高字节在后，如 0x00 0xBC 0x1B,表示实际数据为 7100 W
		int this_power =  (int)StringUtil.float16to10ByParamDesc(data.substring(74, 80), 1);//		
		OmsChargerTelemetryRecord   record  = new OmsChargerTelemetryRecord();
		record.setCharger_id(chargerId);
		record.setVoltage(thisVoltage);
		record.setElectricity(thisElectricity);
		record.setCharger_power(this_power);
		record.setCreate_time(new Date());
		record.setMinites(this_minute);
		record.setValid_flag(1);
		OmsChargerTelemetryRecordDao.save(record);
		//charge_jrnl怎么加，待考虑
//		record.setCharge_jrnl(charge_jrnl);
        code ="200";
        msg="ok";
        String jsonStr =StringUtil.getjsonReturn("", "", code, msg); 
		return jsonStr;
	}

	//所有字段位置按照1.3协议中充电上传报文来重新获取
	@Override
	public String uploadRemotePulse(Map<String,String> map) {
		String data,chargerId,port,code,msg; 
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsChargerPulseRecord record = new OmsChargerPulseRecord();
		float charge_quantity = StringUtil.float16to10ByParamDesc(data.substring(50,58), 100);
		float charge_amount = StringUtil.float16to10ByParamDesc(data.substring(58,64), 100);
//		port = data.substring(0,2);//此处看协议重写
//		int port_int = Integer.parseInt(port, 2);
		record.setCharger_id(chargerId);
		record.setCharge_quantity(charge_quantity);
		record.setCharge_amount(charge_amount);
		record.setCreate_time(new Date());
		record.setValid_flag(1);
		record.setPort(0);
		omsChargerPulseRecordDao.save(record);
        code ="200";
        msg="ok";
        String jsonStr =StringUtil.getjsonReturn("", "", code, msg); 
		return jsonStr;
	}

	@Override
	public String uploadBill(Map<String,String> map) {
		String data,chargerId,jsonStr,responseMsgHeader,requestURL,code,msg; 
//		String[] header = StringUtil.getMessageHeader(data); 
//		String sKeyLink= StringUtil.getSKeyLink(header[5]);	
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
//		String start_time =data.substring(50, 64);
//		start_time =  StringUtil.time14format(start_time);
//		long start_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(start_time).getTime();
//		String end_time =data.substring(64, 78);
//		end_time =  StringUtil.time14format(end_time);
//		long end_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(end_time).getTime();
//		long charge_time = end_time_long - start_time_long;
		String userCard =data.substring(78, 98);
		float start_em = StringUtil.float16to10ByParamDesc(data.substring(98,106), 100); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em = StringUtil.float16to10ByParamDesc(data.substring(106,114), 100); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.float16to10ByParamDesc(data.substring(114,122), 100);//*本次充电电量  与上类似
		float this_amount = StringUtil.float16to10ByParamDesc(data.substring(122,130), 100);//*本次充电金额  与上类似
		float offline_balance_start = StringUtil.float16to10ByParamDesc(data.substring(130,138), 100);//充电前卡余额  与上类似
		float offline_balance_end = StringUtil.float16to10ByParamDesc(data.substring(138,146), 100);//充电后卡余额  与上类似
		float char_bill = StringUtil.float16to10ByParamDesc(data.substring(146,150), 100);//服务费金额  2   与上类似
		String offline_is_pay =data.substring(150, 152);//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
		String charge_end_reason =data.substring(152, 154);//充电结束原因
//		0x01: 后台远程控制正常结束
//		0x02: 本地刷卡控制正常结束
//		0x03: 满足预设停止条件正常结束
//		0x04：电池满电正常结束
		String charge_start_mode = data.substring(154, 156);//充电启动方式 0x00：后台远程启动 0x01: 本地刷卡远程验证启动  0x02：本地刷卡白名单验证启动
		String control_type = data.substring(156, 158);//控制类型  参考控制类型表对应数据，如0x04为自动充满方式。
		String open_restricted_data = data.substring(158, 166);//开启限制数据  自动充满停机方式下无意义。低字节在前，高字节在后。电量控制,单位为“度”，精确到0.01,传输数据放大100倍；时间控制，单位为“秒“，精确到1,；金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
		String vehicle_identification_code = data.substring(166, 200);//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
		omsChargerChargeBillRecord_query.setCharger_id(chargerId);
		omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
		//线上卡是18808开头  线下卡是18806开头
		if(userCard.startsWith("18808")){
			omsChargerChargeBillRecord_query.setOffline_is_pay(2);
		}else{
			if(offline_is_pay_int==1){
				omsChargerChargeBillRecord_query.setOffline_is_pay(1);
			}else{
				omsChargerChargeBillRecord_query.setOffline_is_pay(0);
			}
		}
		omsChargerChargeBillRecord_query.setStatus(4);//4 充电结束 ：桩回复充电结束 ；
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
	        code ="100";
	        msg="charge record not found!";
	        jsonStr =StringUtil.getjsonReturn("", "", code, msg); 
			return jsonStr;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(now);
		long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount(this_amount);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(5);
		omsChargerChargeBillRecord.setValid_flag(1);
		omsChargerChargeBillRecord.setCharge_start_mode(charge_start_mode);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
		omsChargerChargeBillRecord.setControl_type(control_type);
		omsChargerChargeBillRecord.setOpen_restricted_data(open_restricted_data);
		omsChargerChargeBillRecord.setVIN(vehicle_identification_code);
		omsChargerChargeBillRecordDao.save(omsChargerChargeBillRecord);
		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
//        		+"&end_em="+end_em+"&electric_charge="+this_amount+"&serve_charge="+char_bill+"&end_time="+now+"&charge_time="+charge_time;
//        StringUtil.httpGetRequest(requestURL);		
        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
        code ="200";
        msg="ok";
        jsonStr =StringUtil.getjsonReturn(responseMsgHeader, "", code, msg); 
		return jsonStr;
	}
	//1.1的遥信 ，只有交流桩 此方法废弃，因为最新的数据库设计不能满足1.1中报文返回  参见oms_charger_state_alternate[交流充电桩状态表]
	@Override
	public void uploadTelesignal(Map<String, String> map) {
		String data = map.get("data");
		String chargerId = map.get("chargerId");
//		OmsCharger omsCharger_query = new OmsCharger();
//		omsCharger_query.setCharger_id(chargerId);
//		OmsCharger omsCharger = omsChargerDao.findOneExample(omsCharger_query, null, null);
		String charge_status = map.get("charge_status");
		String fault_status = map.get("fault_status");
		String bespeak_status = map.get("bespeak_status");
		String plug_status = map.get("plug_status");
		
		OmsChargerStateAlternate omsChargerStateAlternate_query= new OmsChargerStateAlternate();
		omsChargerStateAlternate_query.setCharger_id(chargerId);
		OmsChargerStateAlternate omsChargerStateAlternate = omsChargerStateAlternateDao.findOneExample(omsChargerStateAlternate_query, null, null);
		if(omsChargerStateAlternate!=null){
			if(StringUtil.isNumeric(charge_status)){
				int charge_status_int = Integer.valueOf(charge_status);
				if(charge_status_int>0){//充电状态	BIN码	1		0x00空闲  0x01充电
					omsChargerStateAlternate.setCharge_status(2);//0: 空闲;1: 预约;2 充电; 3 故障
				}else{
					omsChargerStateAlternate.setCharge_status(0);
				}
			}
			if(StringUtil.isNumeric(fault_status)){
				int fault_status_int = Integer.valueOf(fault_status);
				if(fault_status_int>0){//充电状态	BIN码	1		0x00空闲  0x01充电
					omsChargerStateAlternate.setCharge_status(3);//0: 空闲;1: 预约;2 充电; 3 故障
				}else{
					omsChargerStateAlternate.setCharge_status(0);
				}
			}
			omsChargerStateAlternateDao.updateObject(omsChargerStateAlternate);
		}
//		map.put("charge_status", String.valueOf(charge_status_int));
//		map.put("fault_status", String.valueOf(fault_status_int));
//		map.put("bespeak_status", String.valueOf(bespeak_status_int));
//		map.put("plug_status", String.valueOf(plug_status_int));
	}


	 

}
